from ufile import config, filemanager
from fastapi import FastAPI
import time, os

app = FastAPI()
case_dir = "./testcase"

@app.post("/")
async def chat():
    return {
        "msg": "hello world"
    }

# 执行指定名称的用例
@app.get("/execCaseByName")
async def execCaseByName(case_name: str = "test_users.py"):
    timestamp_str = str(int(time.time()))
    # 遍历用例文件夹，找到指定的用例
    for filepath, dirs, filelist in os.walk(case_dir):
        if case_name in filelist:
            # 创建结果存储的临时文件夹
            allure_result_dir = os.path.join(
                "/tmp",
                "allure_result_" + timestamp_str
            )
            allure_report_dir = os.path.join(
                "/tmp",
                "allure_report_" + timestamp_str
            )
            os.mkdir(allure_result_dir)
            os.mkdir(allure_report_dir)
            # 执行对应的脚本
            os.system("pytest {}  --alluredir={}".format(
                os.path.join(filepath, case_name),
                allure_result_dir
            ))

            # 生成测试报告
            os.system("allure generate {} -o {} --clean".format(allure_result_dir, allure_report_dir))

            # 上传测试报告
            upload_dir(
                allure_report_dir,
                "iftest/{}".format(timestamp_str)
            )

            print("http://tideswing-storehouse-test.cn-bj.ufileos.com/iftest/{}/index.html".format(timestamp_str))

            return {
                "code": 20000,
                "msg": "用例执行成功",
                "data": {
                    "report_url": "http://tideswing-storehouse-test.cn-bj.ufileos.com/iftest/{}/index.html".format(timestamp_str)
                }
            }

    # 未找到对应用例
    return {
        "code": 20000,
        "msg": "未找到对应用例",
        "data": {}
    }

# 执行指定目录的用例
@app.get("/execCaseByCatagory")
async def execCaseByCatagory(catagory_name: str = "users"):
    timestamp_str = str(int(time.time()))
    # 遍历用例文件夹，找到指定的用例
    for filepath, dirs, filelist in os.walk(case_dir):
        if catagory_name in dirs:
            # 创建结果存储的临时文件夹
            allure_result_dir = os.path.join("/tmp", "allure_result_" + timestamp_str)
            allure_report_dir = os.path.join("/tmp", "allure_report_" + timestamp_str)

            os.mkdir(allure_result_dir)
            os.mkdir(allure_report_dir)
            # 执行对应的脚本
            os.system("cd {}&&pytest --alluredir={}".format(
                os.path.join(filepath, catagory_name),
                allure_result_dir
            ))

            # 生成测试报告
            os.system("allure generate {} -o {} --clean".format(allure_result_dir, allure_report_dir))

            # 上传测试报告
            upload_dir(
                allure_report_dir,
                "iftest/{}".format(timestamp_str)
            )

            print("http://tideswing-storehouse-test.cn-bj.ufileos.com/iftest/{}/index.html".format(timestamp_str))

            return {
                "code": 20000,
                "msg": "用例执行成功",
                "data": {
                    "report_url": "http://tideswing-storehouse-test.cn-bj.ufileos.com/iftest/{}/index.html".format(timestamp_str)
                }
            }

    # 未找到对应目录
    return {
        "code": 20000,
        "msg": "未找到对应目录",
        "data": {}
    }


# 对象存储配置
OSS_CONFIG = {
    "public_key": 'TOKEN_0f50d0b8-2af7-4980-84a4-1ff222c07203',
    "private_key": 'ea1c0e4a-b7c7-47de-86de-87bfe12fafb2',
    "bucket": "tideswing-storehouse-test",
    "uploadsuffix": ".cn-bj.ufileos.com",
    "downloadsuffix": ".ufile.ucloud.com.cn"
}
def upload_dir(local_dir, remote_dir):
    public_key = OSS_CONFIG["public_key"] # 账户公钥
    private_key = OSS_CONFIG["private_key"]  # 账户私钥
    bucket = OSS_CONFIG["bucket"]  # 空间名称

    config.set_default(uploadsuffix=OSS_CONFIG["uploadsuffix"])
    config.set_default(downloadsuffix=OSS_CONFIG["downloadsuffix"])

    ufile_handler = filemanager.FileManager(public_key, private_key)

    # 遍历目录文件
    for filepath, dirs, filelist in os.walk(local_dir):
        for filename in filelist:
            curFile = os.path.join(filepath, filename)  # 路径的拼接
            uploadpath = filepath.replace(local_dir, '') + '/'  # 路径的替换
            path, file_name = os.path.split(curFile)  # 分割路径和文件名
            curUploadPath = remote_dir + uploadpath + file_name  # 拼接OSS的上传文件目录路径
            ufile_handler.putfile(
                bucket,
                curUploadPath,
                curFile,
                header=None
            )